﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.SmallPic;
using MINERP.BLL.Common;
using MINERP.DAL;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using System.Collections;

namespace MINERP.BLL.SmallPic
{
    public class SamllPicMainBLL
    {
        public List<ProductView> GetCurTaskList(int curTechid, int printerId)//根据节点ID得到该岗位的任务列表
        {
            List<ProductView> listResult = new List<ProductView>();

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int orderDoing = (int)OrderInfoStatus.Doing;
                foreach (var WFL in db.WorkOrderFlowList.Where(wf => wf.tb_Tech.TechId == curTechid && wf.Status == orderDoing).ToList())
                {
                    #region load data
                    if (!WFL.orderInfoReference.IsLoaded)
                    {
                        WFL.orderInfoReference.Load();
                    }

                    if (WFL.orderInfo.status != (int)OrderInfoStatus.Doing)
                    {
                        continue;
                    }

                    if (!WFL.orderInfo.Tb_OrderBagReference.IsLoaded)
                    {
                        WFL.orderInfo.Tb_OrderBagReference.Load();
                    }
                    if (!WFL.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        WFL.orderInfo.Tb_OrderBag.ShopReference.Load();
                    }
                    if (!WFL.orderInfo.photoInfo.IsLoaded)
                    {
                        WFL.orderInfo.photoInfo.Load();
                    }
                    #endregion
                    bool isReturnOrder = false;
                    NewInnerReturn innerReturn = db.NewInnerReturn.FirstOrDefault(p => p.OrderproductID == WFL.orderInfo.OrderProductId);
                    if (innerReturn != null)
                    {
                        isReturnOrder = true;
                    }


                    ProductView view = new ProductView()
                    {

                        CtmName = WFL.orderInfo.CtmName,
                        IsSelect = false,
                        OrderCode = WFL.orderInfo.OrderProductCode,
                        OrderName = WFL.orderInfo.OrderProductName,
                        OrderPath = WFL.orderInfo.OrilOrderPath,
                        OrderProductId = WFL.orderInfo.OrderProductId,

                        OrderTime = WFL.orderInfo.Tb_OrderBag.OrderTime,
                        Priority = WFL.orderInfo.Priority == null ? 0 : (int)WFL.orderInfo.Priority,
                        Remark = WFL.orderInfo.Remark,
                        ShopName = WFL.orderInfo.Tb_OrderBag.Shop.shopName,
                        OrderNum = WFL.orderInfo.productNum,
                        isRetrun = isReturnOrder
                    };

                    view.Photos = new List<PhotoInfo_Info>();


                    foreach (var pi in WFL.orderInfo.photoInfo.ToList())
                    {
                        if (pi.status == (int)PhotoStatus.Printed)//已打印过的就不加入到此列表
                        {
                            continue;
                        }
                        if (pi.printerId != printerId)
                        {
                            continue;
                        }
                        if (isReturnOrder)
                        {
                            if (pi.status2 != (int)PhotoStatus2.innerReturn)
                            {
                                continue;
                            }
                        }
                        PhotoInfo_Info pinfo = new PhotoInfo_Info()
                        {
                            PicPath = pi.picPath,
                            TotalNum = pi.TotalNum == null ? 1 : (int)pi.TotalNum,
                            Remark = pi.Remark,
                            IsRebackPhoto = pi.status2 == (int)PhotoStatus2.innerReturn ? true : false

                        };
                        view.Photos.Add(pinfo);
                    }
                    if (view.Photos.Count != 0)
                    {
                        listResult.Add(view);
                    }
                }
            }

            return listResult;
        }

        public string GetReportDir(int printerId)//得到扩印模块的照片目录
        {
            string strPath = "";
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                strPath = db.printer.FirstOrDefault(p => p.PrinterID == printerId).hotDirPath;
            }
            return strPath;
        }
        /// <summary>
        /// 完成流程
        /// </summary>
        /// <param name="oiTask"></param>
        /// <param name="curTechId"></param>
        /// <param name="userId"></param>
        /// <param name="printerId"></param>
        /// <returns></returns>
        public bool CompleteTask(ProductView oiTask, int curTechId, int userId, int printerId)//完成
        {
            bool result = true;
            WorkFlowListBLL wflBLL = new WorkFlowListBLL();

            //在photoinfo表中复制记录
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == oiTask.OrderProductId);
                if (oi != null)
                {
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    //ArrayList listAdd = new ArrayList();
                    foreach (var pi in oi.photoInfo.ToList())
                    {
                        if (pi.status == (int)PhotoStatus.Printed)
                        {
                            continue;
                        }
                        if (pi.printerId != printerId)
                        {
                            continue;
                        }
                        //int totalNum = oi.productNum * (pi.TotalNum == null ? 1 : (int)pi.TotalNum);
                        int totalNum = 1 * (pi.TotalNum == null ? 1 : (int)pi.TotalNum);
                        if (!pi.paperFaceReference.IsLoaded)
                        {
                            pi.paperFaceReference.Load();
                        }
                        if (!pi.paperTypeReference.IsLoaded)
                        {
                            pi.paperTypeReference.Load();
                        }
                        pi.TotalNum = 1;
                        pi.status = (int)PhotoStatus.Printed;
                        if (totalNum > 1)
                        {
                            for (int i = 0; i < totalNum - 1; i++)
                            {
                                db.AddTophotoInfo(new photoInfo()
                                {
                                    Height = pi.Height,
                                    IsModifySize = pi.IsModifySize,
                                    MakeUpNum = pi.MakeUpNum,
                                    OldPicPath = pi.OldPicPath,
                                    orderInfo = pi.orderInfo,
                                    paperFace = pi.paperFace,
                                    paperType = pi.paperType,
                                    PhotoBarCode = "00",
                                    photoName = pi.photoName,
                                    picPath = pi.picPath,
                                    pixHeight = pi.pixHeight,
                                    pixWidth = pi.pixWidth,
                                    Remark = pi.Remark,
                                    status = pi.status,
                                    status2 = pi.status2,
                                    TotalNum = 1,
                                    Width = pi.Width,
                                    printerId = pi.printerId,
                                    userId = pi.userId
                                });
                            }
                        }
                    }

                }
                try
                {
                    db.SaveChanges();
                    //更改被复制的条码
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }

                    foreach (var pi in oi.photoInfo.ToList())
                    {
                        pi.PhotoBarCode = "3" + pi.photoId.ToString().PadLeft(9, '0');
                    }

                    db.SaveChanges();
                    bool allPhotoPrinted = true;
                    foreach (var photo in oi.photoInfo)
                    {
                        if (photo.status != (int)PhotoStatus.Printed)
                        {
                            allPhotoPrinted = false;
                            break;
                        }
                    }
                    //改流程
                    if (allPhotoPrinted)
                    {
                        result = wflBLL.OverCurTech(curTechId, userId, oiTask.OrderProductId);
                        if (!result)
                        {
                            return result;
                        }
                    }
                }
                catch (Exception)
                {
                    result = false;
                }

            }

            return result;
        }

        /// <summary>
        /// 打印小票前预分配
        /// </summary>
        /// <param name="orderproductid"></param>
        public string AssignGridForSmallPrint(newSampleYPDBEntities db ,int orderproductid, out string gridName)
        {
            string msg =string.Empty;
            gridName = "无";

            try
            {
                //using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                //{
                    orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderproductid);

                    if (oi != null)
                    {
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }
                        if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                        {
                            oi.Tb_OrderBag.ShopReference.Load();
                        }
                        Grid grid = db.Grid.FirstOrDefault(g => g.SomeId == oi.Tb_OrderBag.Shop.ShopId && g.GridSubArea.Type == (int)SubAreaType.Shop&&g.Status==1);
                        if (grid != null)//该产品所在商户已经占了格子
                        {
                            gridName = grid.GridName;
                        }
                        else//该产品所在商户还未占格子
                        {
                            List<Grid> gridlist = db.Grid.Where(g => g.Status == 0 && g.GridSubArea.Type == (int)SubAreaType.Shop).ToList();
                            if (gridlist.Count < 1)
                            {
                                msg = "没有可用的格子，请检查格子是否已满！";
                            }
                            else
                            {
                                Grid MINGrid = gridlist.OrderBy(g => g.GridName).First();
                                gridName = MINGrid.GridName;
                                MINGrid.SomeId = oi.Tb_OrderBag.Shop.ShopId;
                                MINGrid.Status = 1;
                                MINGrid.FirstEnterTime = DateTime.Now;

                                GridRecord gridrecord = new GridRecord()
                                {
                                    CreateTime = DateTime.Now,
                                    Grid = MINGrid,
                                    Num = 1,
                                    OperateUid = -1,
                                    SomeId = oi.OrderProductId,

                                };
                            }
                        }

                    }
                    else
                    {
                        msg = "没有找到该产品编号";
                    }
                    db.SaveChanges();
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return msg;
        }

        public bool SetExportDir(string p)
        {
            bool result = true;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                FileDirPath f = db.FileDirPath.FirstOrDefault(ft => ft.id == 7);
                if (f != null)
                {
                    f.FileDir = p;
                    result = true;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch
                    {

                        result = false;
                    }
                }
                else
                {
                    result = false;
                }
            }

            return result;
        }

        public ProductView GetProductViewByCode(string strCode)
        {
            ProductView view = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductCode == strCode);
                if (oi != null)
                {
                    #region loadData
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        oi.Tb_OrderBag.ShopReference.Load();
                    }
                    #endregion

                    if (oi != null)
                    {
                        view = new ProductView()
                        {

                            CtmName = oi.CtmName,
                            OrderCode = oi.OrderProductCode,
                            OrderName = oi.OrderProductName,
                            OrderProductId = oi.OrderProductId,
                            Remark = oi.Remark,
                            ShopName = oi.Tb_OrderBag.Shop.shopName,
                            OrderNum = oi.productNum
                        };
                        view.Photos = new List<PhotoInfo_Info>();
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }

                        foreach (var pi in oi.photoInfo.ToList())
                        {
                            view.Photos.Add(new PhotoInfo_Info() { TotalNum = (pi.TotalNum == null ? 1 : (int)pi.TotalNum), PhotoId = pi.photoId });
                        }
                    }
                }
            }
            return view;
        }


        public Printer_Info GetPrinterObj(int id)
        {
            Printer_Info printerInfo = new Printer_Info();
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                printer printerobj = enty.printer.FirstOrDefault(p => p.PrinterID == id);
                printerInfo.HotDirPath = printerobj.hotDirPath;
                printerInfo.ICCPath = printerobj.ICCPath;
                printerInfo.IsTransverse = (bool)printerobj.IsTransverse;
                printerInfo.MonitorDirPath = printerobj.MonitorDirPath;
                printerInfo.PDes = printerobj.PDes;
                printerInfo.PDPI = printerobj.PDPI;
                printerInfo.PLength = printerobj.PLength;
                printerInfo.PName = printerobj.PName;
                printerInfo.PrinterID = printerobj.PrinterID;
                printerInfo.PType = printerobj.PType;
                printerInfo.PWidth = printerobj.PWidth;
                printerInfo.Status = printerobj.status;
                printerInfo.Status2 = (int)printerobj.status2;
                //printerInfo.GridNum = printerobj.GridNum == null ? 0 : (int)printerobj.GridNum;
            }
            return printerInfo;
        }

        /// <summary>
        /// 得到orderInfo
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public MINERP.MODEL.SmallPic.OrderInfo_Info GetOrderInfoToPrintTicket(int orderProductId, int printerId,bool isAssignGrid)
        {
            MINERP.MODEL.SmallPic.OrderInfo_Info oi = new MINERP.MODEL.SmallPic.OrderInfo_Info();
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                string gridName = string.Empty;
                string ret = "";
                if (isAssignGrid)
                {
                    ret = AssignGridForSmallPrint(enty, orderProductId, out gridName);
                }
                //string ret = AssignGridForSmallPrint(enty, orderProductId, out gridName);
                MINERP.MODEL.SmallPic.OrderInfo_Info orderInfo_info = new MINERP.MODEL.SmallPic.OrderInfo_Info();
                List<PhotoInfo_Info> listPhoto = new List<PhotoInfo_Info>();

                orderInfo orderinfo = enty.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                NewInnerReturn innerReturn = enty.NewInnerReturn.FirstOrDefault(p => p.OrderproductID == orderProductId);
                bool isReturnOrder = false;
                if (innerReturn != null)
                {
                    isReturnOrder = true;

                }
                if (!orderinfo.photoInfo.IsLoaded)
                {
                    orderinfo.photoInfo.Load();
                }
                if (orderinfo != null)
                {
                    orderinfo.Tb_OrderBagReference.Load();
                    orderinfo.Tb_OrderBag.ShopReference.Load();
                }
                if (!orderinfo.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    orderinfo.Tb_OrderBag.ShopReference.Load();
                }
                if (!orderinfo.WorkOrderFlowList.IsLoaded)
                {
                    orderinfo.WorkOrderFlowList.Load();
                }
                if (!orderinfo.Tb_ProductReference.IsLoaded)
                {
                    orderinfo.Tb_ProductReference.Load();
                }
                if(!orderinfo.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                {
                    orderinfo.Tb_Product.Tb_PorductCategoryReference.Load();
                }
                if(!orderinfo.photoInfo.FirstOrDefault().paperFaceReference.IsLoaded)
                {
                    orderinfo.photoInfo.FirstOrDefault().paperFaceReference.Load();
                }
                if (!orderinfo.photoInfo.FirstOrDefault().paperTypeReference.IsLoaded)
                {
                    orderinfo.photoInfo.FirstOrDefault().paperTypeReference.Load();
                }
                int TotalNumInBag = orderinfo.Tb_OrderBag.orderInfo.Count();
                int OrderInBag = orderinfo.Tb_OrderBag.orderInfo.Count(c => c.OrderProductId >= orderinfo.OrderProductId);
                oi.ProductOrderInBag = OrderInBag + "-" + TotalNumInBag + "-" + orderinfo.Tb_OrderBag.OrderBagId;
                int photoNum = 0;
                int totalPhotoNum = 0;
                int innerreturnPhoto = (int)PhotoStatus2.innerReturn;
                if (isReturnOrder)
                {
                    foreach (var item in orderinfo.photoInfo.Where(p => p.status2 == innerreturnPhoto))
                    {
                        if (item.printerId == printerId)
                        {
                            PhotoInfo_Info photoInfo_info = new PhotoInfo_Info();
                            photoInfo_info.Height = item.Height;
                            photoInfo_info.Width = item.Width;
                            listPhoto.Add(photoInfo_info);
                        }
                    }
                    totalPhotoNum = listPhoto.Count;

                }
                else
                {
                    foreach (var item in orderinfo.photoInfo)
                    {
                        if (item.printerId == printerId)
                        {
                            for (int i = 0; i < item.TotalNum * orderinfo.productNum; i++)
                            {
                                PhotoInfo_Info photoInfo_info = new PhotoInfo_Info();
                                photoInfo_info.Height = item.Height;
                                photoInfo_info.Width = item.Width;
                                listPhoto.Add(photoInfo_info);
                            }
                            photoNum += (int)item.TotalNum;
                        }
                        totalPhotoNum += (int)item.TotalNum;
                    }
                }
                //Grid GRID = enty.Grid.FirstOrDefault(G => G.SomeId == orderinfo.Tb_OrderBag.Shop.ShopId);
                //if (GRID != null)
                //{
                //    oi.ShopGridName = GRID.GridName;
                //}
                //else
                //{
                //    oi.ShopGridName = "无";
                //}
                oi.ShopGridName = gridName;
                oi.OrderProductId = orderinfo.OrderProductId;
                oi.OrderProductName = orderinfo.OrderProductName;
                oi.CtmName = orderinfo.CtmName;
                oi.Priority = (int)orderinfo.Priority;
                oi.Remark = orderinfo.Remark;
                oi.PhotoInfoList = listPhoto;
                oi.PhotoNumAndTotalNum = photoNum.ToString() + "/" + totalPhotoNum.ToString();
                oi.ShopName = orderinfo.Tb_OrderBag.Shop.shopName;
                oi.PaperTypeName = orderinfo.photoInfo.FirstOrDefault().paperType.Name;
                oi.PaperFaceName = orderinfo.photoInfo.FirstOrDefault().paperFace.Name;
                oi.ProductType = orderinfo.ProductType;
                oi.ProductCaName = orderinfo.Tb_Product.Tb_PorductCategory.ProductCategoryName;
                oi.OrderTime = orderinfo.Tb_OrderBag.OrderTime;
                oi.FetchTime = orderinfo.Tb_OrderBag.FetchTime;



                WorkOrderFlowList nextFlow = orderinfo.WorkOrderFlowList.Where(p => p.Status == 0).OrderBy(p => p.WorkOrder).FirstOrDefault();
                if (nextFlow == null)
                {
                    oi.NextTech = "生产完成补打票";
                }
                else
                {
                    nextFlow.tb_TechReference.Load();
                    oi.NextTech = nextFlow.tb_Tech.TechName;
                }
                if (isReturnOrder)
                {
                    oi.OrderProductName += "_内部返单";
                }
            }
            return oi;
        }
    }
}
